package com.casework

import static javax.servlet.http.HttpServletResponse.*
import org.springframework.web.multipart.MultipartFile

class AttachedFileController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def parseXmlService
    def exportDBService

    def exportDB = {
        try{
            exportDBService.exportDB()
            render text: "all done"

        }catch(e){
            render text:'failure'
        }
    }

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [attachedFileInstanceList: AttachedFile.list(params), attachedFileInstanceTotal: AttachedFile.count()]
    }

    def create = {
        def caseId = params.remove('caseId')
        def attachedFileInstance = new AttachedFile()
        attachedFileInstance.properties = params
        return [attachedFileInstance: attachedFileInstance, caseId: caseId]
    }

    def bulkupload ={
        amazonS3Service.pushAllFiles()
        render 'all done dude -for real'
    }

    def save = { AttachedFileCommand command ->
        if (!command.legalCase) {
            render text: 'unable to create file without case'
        }

        if (!command.file.isEmpty()) {
            // success

            String ecNumber = command.legalCase.ecNumber
            String path = ecNumber + '/' + command.file.getOriginalFilename().replace(" ", "-")
            String file = command.file.getOriginalFilename().replace(" ", "_");
            String ext = file.substring(file.lastIndexOf(".") + 1);

            def attachedFile = new AttachedFile(path: path, internalFileOnly: command.internalFileOnly, contentType: ext)
            
            command.legalCase.addToFiles(attachedFile).save(failOnError: true, flush: true)

            amazonS3Service.put(command.file.getInputStream(), path, ecNumber, ext, command.file.getSize())

        }

        redirect(controller: 'legalCase', action: "show", id: command.legalCase.id)
    }


    def amazonS3Service;
    def uploadfile = {

        if (request.method == 'POST') {

            Iterator itr = request.getFileNames();

            String vloc = "";
            while (itr.hasNext()) {
                MultipartFile mpFile = request.getFile(itr.next());
                if (!mpFile.isEmpty()) {
                    // success
                    String _file = mpFile.getOriginalFilename().replace(" ", "_");
                    vloc += h.uid + "/" + _file;
                    String ext = _file.substring(_file.lastIndexOf(".") + 1);
                    amazonS3Service.put(mpFile.getInputStream(), _file, h.uid, ext, mpFile.getSize())

                }
            }

            render vloc
        }
    }


    def parseFile = {AttachedFileCommand command ->
        def file = new File('temp2.txt')
        try {
            file << command.file.bytes
            if(file.text.contains('<lngNACEShortDescriptionID>4</lngNACEShortDescriptionID>')){
                parseXmlService.parseEverything(file.text)
            } else{
                parseXmlService.parseFiles(file.text)
            }
            render 'awesome thanks'
        } finally {
            file.delete()
        }
    }


    def show = {
        def attachedFileInstance = AttachedFile.get(params.id)
        if (!attachedFileInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'attachedFile.label', default: 'AttachedFile'), params.id])}"
            redirect(action: "list")
        }
        else {
            [attachedFileInstance: attachedFileInstance]
        }
    }

    def showFile = {

        def attachedFile = AttachedFile.get(params.fileId)
        if (!attachedFile) {
            response.sendError SC_NOT_FOUND
            return
        }
        def file = new File(attachedFile.path)
        response.contentType = attachedFile.contentType
        response.outputStream << file.bytes
        response.outputStream.flush()
        response.outputStream.close()
    }

    def edit = {
        def attachedFileInstance = AttachedFile.get(params.id)
        if (!attachedFileInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'attachedFile.label', default: 'AttachedFile'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [attachedFileInstance: attachedFileInstance]
        }
    }

}
class AttachedFileCommand {
    MultipartFile file
    boolean internalFileOnly = false
    LegalCase legalCase
}
